﻿namespace Digitalmes.Application.Mes;

/// <summary>
/// 设备警报状态报表
/// </summary>
[ApiExplorerSettings(GroupName = "mes")]
[AllowAnonymous]
public sealed class ReportEquipAlarmService : IDynamicWebApiService
{
    private readonly SugarRepository<EquipAlarmRecord> _alarmRecordRepo;

    public ReportEquipAlarmService(SugarRepository<EquipAlarmRecord> alarmRecordRepo)
    {
        _alarmRecordRepo = alarmRecordRepo;
    }

    /// <summary>
    /// 获取设备警报信息
    /// </summary>
    /// <param name="seconds"></param>
    /// <returns></returns>
    [HttpGet]
    public async Task<List<EquipAlarmRecordDto>> GetAlarmsAsync(int seconds = 60)
    {
        var time = DateTime.Now.AddSeconds(seconds * -1);
        var query = await _alarmRecordRepo.AsQueryable()
            .OrderByDescending(s => s.Id)
            .Where(s => s.StartTime > time && s.Status == 1)
            .ToListAsync();

        return query.Adapt<List<EquipAlarmRecordDto>>();
    }

    /// <summary>
    /// 警报按分类分组
    /// </summary>
    /// <param name="days"></param>
    /// <returns></returns>
    [HttpGet]
    public async Task<object> GetGroupClassifyAsync(int days = 30)
    {
        var time = DateTime.Now.AddDays(days * -1).Date;
        var query = await _alarmRecordRepo.AsQueryable()
            .GroupBy(s => s.Classify)
            .Where(s => s.StartTime >= time)
            .Select(s => new
            {
                name = s.Classify,
                count = SqlFunc.AggregateCount(s.Id),
            })
            .ToListAsync();

        return query;
    }
}
